<?php
/*
 * Copyright (C) 2006 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * @author pablif@gmail.com
 */
require_once('../library/gb-authentication.php');
require_once('../library/gb-feeds.php');
require_once('../library/gb-http.php');
require_once('../library/gb-items.php');

session_start();

#define('PROXY', 'http://192.168.128.150:3128');
define('PROXY', null);

$action = @$_GET['action'];
if(empty($action)) {
  $action = null;
}

$is_authenticated = isset($_SESSION['gb_token']);
if($action == 'auth' || isset($_GET['token'])) {
  if(!array_key_exists('gb_token', $_SESSION)) {
    if(array_key_exists('token', $_GET)) {
      $gbhttp = new GoogleBaseHttpRequest(PROXY);
      $response = gb_get_session_token($_GET['token'], $gbhttp);
      if(!$response->hasErrors()) {
        $_SESSION['gb_token'] = $response->getParsedToken();
        $is_authenticated = true;
      }
      $gbhttp->close();
    } else {
      header("Location: " . gb_get_authentication_url());
    }
  }
}

?>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
      body {
        font-family: Tahoma, Sans;
        font-size: 11px;
        text-align: center;
      }
      table#items {
        font-size: 1em;
        border: 1px solid #ccc;
        border-collapse: collapse;
      }
      table#items td {
        border: 1px solid #ccc;
        vertical-align: top;
        padding: 5px;
      }
      table.gattrs { font-size: 1em; }
      table.gattrs td { padding: 0; }
      #nav {
        width: 700px;
        margin: auto;
        padding: 5px;
      }
    </style>
</head>
<body>

<div id="header">
  <h1>Google Base API demo</h1>
</div>
<div id="nav">
  <?php if(!$is_authenticated):?>
    <a href="?action=auth">login to google base</a>
  <?php endif; ?>
  <a href="?action=new">submit a new item</a>
  <a href="?action=query">query google base items</a>
</div>
<?php if($action == 'new'): ?>
  <h2 style="text-align: left">submit a new item</h2>
  <?php if(isset($_POST['submit'])): ?>
  <?php
    //var_dump($_POST);
    $item = new GoogleBaseItem();
    $item->setDraftStatus(true);
    $item->setDryRunStatus((bool)@$_POST['dry-run']);
    $item->setAuthor(@$_POST['author-name'], @$_POST['author-email']);
    if(isset($_POST['title']) && $_POST['title']!='') $item->setTitle($_POST['title']);
    if(isset($_POST['desc']) && $_POST['desc']!='') $item->setDescription($_POST['desc']);
    if(isset($_POST['link']) && $_POST['link']!='') $item->setLink($_POST['link']);
    if(isset($_POST['attrs']) && !empty($_POST['attrs'])) {
      if(isset($_POST['custom-attr']) && $_POST['custom-attr']!='' &&
         isset($_POST['custom-attr']) && $_POST['custom-attr']!='') {
        $_POST['attrs'][$_POST['custom-attr']] = $_POST['custom-value'];
      }
      foreach($_POST['attrs'] as $name => $value) {
        if(!is_array($value))
          $value = array($value);
        foreach($value as $v)
          $item->addGbaseAttribute($name, $v);
      }
    }
    $gbh = new GoogleBaseHttpRequest(PROXY);
    $response = $item->save($_SESSION['gb_token'], $gbh);
    if($response->hasErrors()) {
      echo 'there was an error uploading the item:';
      echo '<xmp>status code: '.$response->getStatusCode()."\n";
      echo $response->getResponseBody().'</xmp>';
      echo '<xmp>';
      var_dump($item);
      echo '</xmp>';
    } else {
      echo 'item uploaded succesfully!';
    }
  ?>
  <?php else: ?>
    <form action="" method="post" style="text-align: left">
      <input type="checkbox" checked="checked" id="dry-run" name="dry-run">
      <label for="dry-run">dry-run: </label><br>
      <label for="author-name">author name: </label><br>
      <input type="text" id="author-name" name="author-name" value=""><br>
      <label for="author-email">author email: </label><br>
      <input type="text" id="author-email" name="author-email" value=""><br>
      <label for="title">title: </label><br>
      <input type="text" id="title" name="title" value="cool chicken"><br>
      <label for="desc">description: </label><br>
      <input type="text" id="desc" name="desc" value="a chicken that... tastes good"><br>
      <label for="link">link: </label><br>
      <input type="text" id="link" name="link" value="http://example.com/?a=chicken"><br>
      <label for="item-type">item type: </label><br>
      <input type="text" id="item-type" name="attrs[item_type]" value="Recipes"><br>
      <label for="main-ingredient1">main ingredient: </label><br>
      <input type="text" id="main-ingredient1" name="attrs[main_ingredient][]" value="chicken"><br>
      <label for="main-ingredient2">main ingredient: </label><br>
      <input type="text" id="main-ingredient2" name="attrs[main_ingredient][]" value="magic"><br>
      <label for="preparation-time">preparation time: </label><br>
      <input type="text" id="preparation-time" name="attrs[preparation_time]" value="34"><br>
      <label for="custom-attr">another custom attribute: </label><br>
      <input type="text" id="custom-attr" name="custom-attr" value=""> = 
      <input type="text" id="custom-value" name="custom-value" value=""><br>
      <input type="submit" name="submit" value="submit">
      <!--
      <label for=""></label>
      <input type="text" id="" name="" value=""><br>
      -->
    </form>
  <?php endif; ?>
<? elseif($action == 'query'): ?>
  <h2>query the gbase feeds</h2>
  <form action="" method="post" style="margin-top: 20px">
    <label for="query">query: </label>
    <input type="text" id="query" name="query" value="<?php echo @$_POST['query'] ?>">
    <select name="feed">
      <option value="customer" <?php if(@$_POST['feed'] === 'customer') echo 'selected="selected"'; ?>>your items</option>
      <option value="snippets" <?php if(@$_POST['feed'] === 'snippets') echo 'selected="selected"'; ?>>snippets feed</option>
      <option value="by-id" <?php if(@$_POST['feed'] === 'by-id') echo 'selected="selected"'; ?>>get item by id</option>
    </select>
    <input type="submit" name="submit" value="submit">
  </form>
  <?php if(isset($_POST['submit'])):
    $gbhttp = new GoogleBaseHttpRequest(PROXY);
    $feed = new GoogleBaseFeed($gbhttp);
    $url = GBASE_SNIPPET_FEED_URL;
    if(isset($_POST['feed']) && $_POST['feed'] != '') {
      switch($_POST['feed']) {
        case 'customer': $url = GBASE_ITEM_FEED_URL; break;
        case 'snippets': $url = GBASE_SNIPPET_FEED_URL; break;
        case 'by-id': $url = $_POST['query']; break;
      }
    }
    if(@$_POST['feed'] !== 'by-id') {
      $query = new GoogleBaseQuery($url);
      if(isset($_POST['query']) && $_POST['query'] != '')
        $query->setBq($_POST['query']);
      $response = $feed->queryFeed($query, @$_SESSION['gb_token']);
      $entries = $feed->getEntries();
    } else {
      $entries = array($feed->getItem($url, $_SESSION['gb_token']));
      $response = $feed->getResponse();
    }
    
    if(!$response->hasErrors() && !empty($entries)) {
      echo '<table id="items">';
      foreach($entries as $e) {
        $link = $e->getLink(); $title = $e->getTitle(); $desc = $e->getDescription();
        $imglink = $e->getGbaseAttribute('image_link'); $id = $e->getId();
        ?>
        <tr>
          <td><?php if(!empty($imglink)) echo '<img height="50" src="'.$imglink[0]->getValue().'">'; else echo '&lt;no image&gt;';?></td>
          <td>
            <?php if($link): ?>
              <a href="<?php echo $link->getAttributeValue('href'); ?>"><?php echo $title->getValue();?></a>
            <?php else: ?>
              <?php echo $title->getValue();?>
            <?php endif; ?>
          </td>
          <td><?php echo $desc->getValue();?></td>
          <td>
            <table class="gattrs">
              <tr>
                <td>gbase id</td>
                <td><?php echo $id; ?></td>
              </tr>
              <?php foreach($e->getGbaseAttributes() as $attr) { ?>
              <tr>
                <td><?php echo $attr->getName();?></td>
                <td><?php echo $attr->getValue();?></td>
              </tr>
              <?php } ?>
            </table>
          </td>
        </tr>
      <?php }
      echo '</table>';
    } else {
      if($response->hasErrors()) {
        echo 'an error occurred:<br>';
        echo '<xmp>'.$response->getResponseBody().'</xmp>';
      }
    }
  endif; ?>
<? elseif($action == 'edit'): ?>
<? elseif($action == 'edit'): ?>
<? endif; ?>

</body>
</html>
